const util = require('../../utils/util.js')
let p

Page({

	data: {
		staticDomain: util.config('staticDomain'),
		noticeList: [],
		problemList: [],
		signRankList: [],
		scoreRankList: [],
		logined: false,
		loadingPanel: {
			tip: '构建中'
		}
	},

	onLoad: function () {
		p = this
		util.checkLogin({
			success: () => {
				util.checkCommonData({
					success: (commonData) => {
						const { noticeList, problemList, signRankList, scoreRankList } = commonData
						p.setData({
							noticeList,
							problemList,
							signRankList,
							scoreRankList,
							logined: true
						})
						util.hideLoadingPanel(p)
					},
					fail: (code, msg) => {
						p.setData({
							logined: false
						})
						util.hideLoadingPanel(p)
						util.error('首页获取数据失败', '无法获取到首页数据哦，请检查网络稍后再试~')
					}
				})
			},
			fail: () => {
				p.setData({
					logined: false
				})
				util.hideLoadingPanel(p)
			}
		})
	},

	onUnload: function () {
		util.unloadPage('home')
	},

	onShow: () => {
		if (util.globalData('logined') != p.data.logined)
			p.setData({
				logined: util.globalData('logined')
			})
		if (util.globalData('logined') && util.globalData('commonData')) {
			const { noticeList, problemList, signRankList, scoreRankList } = util.globalData('commonData')
			p.setData({
				noticeList,
				problemList,
				signRankList,
				scoreRankList
			})
		}
	},

	goProblem: (e) => {
		util.goPage('problem', {
			problemId: e.currentTarget.dataset.id
		})
	},

	goApply: () => {
		util.goPage('apply')
	},

	previewPhoto: (e) => {
		const url = e.currentTarget.dataset.url
		if (!url)
			return
		wx.previewImage({
			urls: [url],
		})
	},

	onPullDownRefresh: function () {
		wx.stopPullDownRefresh()
		if (!util.globalData('logined') || p.data.loadingPanel.tip)
			return
		util.showLoadingPanel(p, '构建中')
		util.checkCommonData({
			sync: true,
			success: (commonData) => {
				const { noticeList, problemList, signRankList, scoreRankList } = commonData
				p.setData({
					noticeList,
					problemList,
					signRankList,
					scoreRankList
				})
				util.hideLoadingPanel(p)
			},
			fail: (code, msg) => {
				util.hideLoadingPanel(p)
				util.error('刷新首页数据失败', '无法获取到首页数据哦，请检查网络稍后再试~')
			}
		})
	},

	onShareAppMessage: function () {
		return {
			title: '微科创，让你如虎添翼',
			path: '/pages/home/home'
		}
	}
	
})